import { ref } from 'vue'

const STORAGE_KEY = 'shop_fav_v1'

function load(): Record<string, boolean> {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : {}
  } catch {
    return {}
  }
}

function save(map: Record<string, boolean>) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(map))
}

const favMap = ref<Record<string, boolean>>(load())

export function useFavorites() {
  function isFav(id: string | number) {
    return !!favMap.value[String(id)]
  }

  function toggle(id: string | number) {
    const key = String(id)
    favMap.value[key] = !favMap.value[key]
    save(favMap.value)
    return favMap.value[key]
  }

  return { isFav, toggle }
}

